<?php
class Location_model extends Base_Model
{
    public function __construct()
    {
        parent::__construct();
        $this->load->database();
    }

    public function saveLocDataToRedis()
    {
        $res = $this->getLocData();

        $this->load->model("redis_model");
        $redis = $this->redis_model->getRedisInstance();
        $redis->multi();
        foreach ($res['provincelist'] as $p){
            $redis->zAdd('data:province',$p['provinceID'],$p['province']);
        }
        $redis->set('data:city',$res['citylist']);
        foreach ($res['cityofprov'] as $k => $d1){
            foreach ($d1 as $dc){
                $redis->zAdd('province:'.$k,$dc['cityID'],$dc['city']);
            }
        }
        foreach ($res['areaofcity'] as $k => $d2){
            foreach ($d2 as $da){
                $redis->zAdd('city:'.$k,$da['areaID'],$da['area']);
            }
        }
        $redis->exec();
    }

    public function delLocData()
    {
        $res = $this->getLocData();
        $keys = array();
        foreach ($res['cityofprov'] as $k1 => $d1){
            $keys[] = 'province:'.$k1;
        }
        foreach ($res['areaofcity'] as $k2 => $d2){
            $keys[] = 'city:'.$k2;
        }
        $keys[] = 'data:province';
        $keys[] = 'data:city';
        $this->load->model("redis_model");
        $redis = $this->redis_model->getRedisInstance();
        $redis->delete($keys);
    }

    public function getLocData()
    {
        $data1 = array();
        $data2 = array();
        $province = $this->db->select('provinceID,province')->from('mod_province')->get()->result_array();
        $city = $this->db->select('cityID,city')->from('mod_city')->get()->result_array();
        $citystr = igbinary_serialize($this->getCityList());
        foreach ($province as $row){
            $c = $this->db->select('cityID,city')->from('mod_city')->where('fatherID',$row['provinceID'])->get()->result_array();
            $data1[$row['provinceID']] = $c;
        }
        foreach ($city as $row){
            $a = $this->db->select('areaID,area')->from('mod_area')->where('fatherID',$row['cityID'])->get()->result_array();
            $data2[$row['cityID']] = $a;
        }

        return array('citylist'=>$citystr,'provincelist'=>$province,'areaofcity'=>$data2,'cityofprov'=>$data1);
    }

    public function getCityList()
    {
        $citys = $this->db->select('c.cityID,c.city,p.province,p.provinceID')->from('mod_city as c')->join('mod_province as p','c.fatherID=p.provinceID')->get()->result_array();
        $res = array();
        foreach ($citys as $c){
            $res[$c['provinceID']]['province'] = $c['province'];
            $res[$c['provinceID']]['citys'][]  = array('cityid'=>$c['cityID'],'city'=>$c['city']);
        }
        return array_values($res);
    }
}